package org.lee.mq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

/**
 * @author jackielee
 * @version 1.0
 * @description SpringContextHolder
 * @date 2021/7/5
 **/
@Component
@Slf4j
public class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }

    public static <T> boolean registerBean(String name, T bean) {
        ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
        context.getBeanFactory().registerSingleton(name, bean);
        log.debug("SpringContextHolder 注册 {} 到 spring容器", bean);
        return true;
    }

    public static <T> T getBean(Class<T> type) {
        return applicationContext.getBean(type);
    }
}
